/*
 * Copyright (c) 2006-2021, Halo team
 *
 * SPDX-License-Identifier: GPLv3
 *
 * Change Logs:
 * Date           Author       Notes
 * 2021-09-11     Eywen        the first version
 */


#include "endstop.h"

static void endstop_level_changed_event(void *args)
{
    endstop_t *endstop;
    endstop = (endstop_t *)args;
    //motion_step_t *motion_step;
    //motion_step = endstop->motion_step_relevancy;
    smart_step_t *smart_step;
    smart_step = endstop->motion_step_relevancy->step_drv;
    /* 触发了限位开关 */
    /* 复位脉冲计数值,便于计算当前步进电机的位置 */
    smart_step->ops->reset_cur_pulse_loc(smart_step);
}

/* 初始化限位开为关 */
bool endstop_init(endstop_t *device, int pin, bool release_level,
                  motion_step_t *step)
{
    ASSERT_NULL(device);
    ASSERT_NULL(step);

    device->pin = pin;
    device->motion_step_relevancy = step;
    device->release_level = release_level;

    rt_pin_mode(device->pin, PIN_MODE_INPUT_PULLUP);

    rt_uint32_t pin_irq_mode;
    /* 如果正常是高电平,则打开下降沿触发,反之则打开上升言触发 */
    pin_irq_mode = (release_level == PIN_HIGH) ? PIN_IRQ_MODE_FALLING :
                                                 PIN_IRQ_MODE_RISING;
    /* 绑定中断触发 */
    rt_pin_attach_irq(device->pin, pin_irq_mode,
                             endstop_level_changed_event, (void *)device);
    rt_pin_irq_enable(device->pin, true);

    return true;
}

/* 注册限位开关到系统表中,后便后续查看 */
bool endstop_register(endstop_t *device)
{
    UNUSED(device);
    return true;
}

bool bind_endstop_motion_step(endstop_t *endstop, motion_step_t *step)
{
    ASSERT_NULL(endstop);
    ASSERT_NULL(step);

    endstop->motion_step_relevancy = step;

    return true;
}
